#!/bin/bash
# assume squashfs 4.0

. /etc/DISTRO_SPECS

export TEXTDOMAIN=filemnt
export OUTPUT_CHARSET=UTF-8
. gettext.sh

imgFile="$1"
[ ! -f "$imgFile" ] && echo "No regular file: $imgFile" && exit 1
imgFileBASE=${imgFile##*/} ## imgFileBASE="`basename "$imgFile"`" #BK
[ "$(dirname "$imgFile")" = "." ] && imgFile=$(pwd)/${imgFileBASE}

# may need to replace with /mnt/home...
HOMELINK="`readlink /mnt/home`"
case $HOMELINK in *initrd*)
  imgFile="`echo -n "$imgFile" | sed -e "s%${HOMELINK}%/mnt/home%"`"
  #ex: /initrd/mnt/dev_save/kernel_src-3.0.7-patched.sfs becomes /mnt/home/kernel_src-3.0.7-patched.sfs
esac

#ex: /mnt/home/kernel_src-3.0.7-patched.sfs becomes /mnt/+mnt+home+kernel_src-3.0.7-patched.sfs
MOUNTPOINT='/mnt/'"`echo "$imgFile" |sed "s#^\.##g" |sed "s#/#+#g" | tr ' ' '_'`" # SFR, added 'tr'
# BK is it already mounted?
MNTEDLOOP="$(cat /proc/mounts | grep -F " $MOUNTPOINT " | cut -f 1 -d ' ')"
[ ! -z $MNTEDLOOP ] && MNTEDLOOP=$(echo "$MNTEDLOOP" | sed 's|/dev/loop/|/dev/loop|') 

if [ "$MNTEDLOOP" = "" ];then #not mounted on $MOUNTPOINT

  Ext=${imgFile##*.} #get file extension   ## Ext=`echo "$imgFile" |sed 's/^.*\.//'`
  Ext=${Ext,,}       #convert to lowercase ## Ext=`echo $Ext | tr [:upper:] [:lower:]`
  case ${Ext} in
    2fs) Type='ext2'     ; check_luks=yes ;;
    3fs) Type='ext3'     ; check_luks=yes ;;
    4fs) Type='ext4'     ; check_luks=yes ;;
    sfs) Type='squashfs' ;;
    iso) Type='iso'      ;;
    wim) Type='wim'      ;;
    *) Type=$(blkid "$imgFile" | grep -o ' TYPE=.*' | cut -f 2 -d '"') ;;
  esac
  if [ "$Type" = "" ] ; then
    echo "Unrecognized format"
    exit 1
  fi
  if [ "$Type" = "wim" ] ; then
    if ! which wimmountrw ; then
      echo "You must install wimlib - https://wimlib.net/"
      exit 1
    fi
  fi
  echo -e "\nType=${Type}\n"

  if [ "$check_luks" = "yes" ] ; then
    Type2=$(blkid "$imgFile" | grep -o ' TYPE=.*' | cut -f 2 -d '"')
    [ "$Type2" = "crypto_LUKS" ] && Type="$Type2"
  fi

  if [ "$Type" = "squashfs" ];then
      . /etc/rc.d/BOOTCONFIG # 140609 add contextual Install/Uninstall button
      echo $EXTRASFSLIST > /tmp/sfsloaded
      if [ "`grep $imgFileBASE /tmp/sfsloaded`" != "" ];then
        LABELINSTALL="$(gettext 'Uninstall SFS')"
        TEXTINSTALL="$(gettext 'uninstall it')"
      else
        LABELINSTALL="$(gettext 'Install SFS')"
        TEXTINSTALL="$(gettext 'install it')"
      fi
      SFSMSG1a="$(eval_gettext "You can choose to mount the \${imgFileBASE} file to view it's contents (read-only), or you can \${TEXTINSTALL}.")" #'geany
      SFSMSG1b="${SFSMSG1a}\n\n$(gettext 'Regarding the latter, traditionally SFS files are selected by the \ZbBootManager\ZB for loading at bootup (see System menu), which you can do, or you can choose to install (load) it now (which will not require a reboot).\n\nNote1: If you want to edit the contents of an SFS file, you have to use the commandline utilities \Zbunsquashfs\ZB and \Zbmksquashfs\ZB.\nNote2: In the case of a full HD installation, without a layered filesystem, installation is irreversible. For all other installation modes, the BootManager can be used to unload an installed (loaded) SFS file.')"
      pupdialog --colors --background '#FFFF80' --backtitle "${imgFileBASE}" --extra-button --yes-label "$(gettext 'View contents')" --no-label "$LABELINSTALL" --extra-label "$(gettext 'Cancel')"  --yesno "${SFSMSG1b}" 0 0
      RETVAL=$?
      [ $RETVAL -eq 1 ] && exec sfs_load "$1"
      [ $RETVAL -ne 0 ] && exit #120527
  fi

  echo -e "\n ### Mount: $imgFile\n"
  mkdir -p "$MOUNTPOINT"

  #111110 handle encrypted save-files...
  CRYPTO=""; Err=0
  DEVLOOP="`losetup -f`" #next free loop device.
  case $Type in ext2|ext3|ext4)
    case $imgFileBASE in
     *_cryptx*) #light encryption.
      CRYPTO='-e 1'
      modprobe cryptoloop
     ;;
     *_crypt*) #heavy encryption.
      CRYPTO='-e aes'
      modprobe cryptoloop
      modprobe aes_generic 2>/dev/null #v407 aes name change.
      modprobe aes 2>/dev/null #for older kernel <2.6.25
      modprobe crypto_blkcipher 2>/dev/null #v407 blkcipher name change.
      modprobe blkcipher 2>/dev/null #old kernel.
      modprobe cbc
     ;;
    esac
  esac

  if [ "$CRYPTO" ];then
    Err=1
    MYPASS="$(/usr/lib/gtkdialog/box_passwd "$(gettext 'Password required')" "$(gettext 'Password required to open') ${imgFileBASE}")"
    if [ $? -eq 0 ] ; then
      echo "$MYPASS" | losetup-222 -p 0 ${CRYPTO} $DEVLOOP "$imgFile"
      if [ $? -eq 0 ] ; then
        mount -t $Type $DEVLOOP "$MOUNTPOINT" && Err=0
      fi
    fi

  else #normal, no encryption... 130204 mavrothal: fix spaces in imgFile...
    case $Type in 
      iso|udf|iso9660) #iso img might have more than 1 fs. prefer udf..
         mount -t udf -o loop "$imgFile" "$MOUNTPOINT" || mount -t iso9660 -o loop "$imgFile" "$MOUNTPOINT"
         ;;
      exfat)
         mount -t exfat -o loop "$imgFile" "$MOUNTPOINT" || {
            # musl static mount.exfat fails
            # have to set loop device manually...
            losetup $DEVLOOP "$imgFile"
            mount.exfat-fuse $DEVLOOP "$MOUNTPOINT"
         }
         ;;
      crypto_LUKS) mount.crypto_LUKS file "$imgFile" "$MOUNTPOINT" ;; # /sbin/mount.crypto_LUKS
      ntfs)
         losetup $DEVLOOP "$imgFile"
         mount -t ntfs $DEVLOOP "$MOUNTPOINT"
         ;;
      wim)
         wimmountrw "$imgFile" "$MOUNTPOINT" || \
           wimmount "$imgFile" "$MOUNTPOINT"
         ;;
      *) 
         mount -t $Type -o loop,rw "$imgFile" "$MOUNTPOINT"
         ;;
    esac
    Err=$?
  fi

  if [ $Err -eq 0 ] ;then
    /usr/lib/gtkdialog/box_splash -timeout 6 -bg green -text "`eval_gettext \"Click \\\$imgFileBASE icon again to unmount it\"`" &
    grep -q -m1 -i 'rox' /usr/local/bin/defaultfilemanager || NEWWINDOW=-n
    defaultfilemanager $NEWWINDOW "$MOUNTPOINT" &
  else
    [ "$CRYPTO" ] && losetup-222 -d $DEVLOOP
    rm -rf "$MOUNTPOINT" #121203
  fi


#### mounted ####
else

  mntinfo=$(mount | grep " $MOUNTPOINT ")
  ## file's mounted, unmount it
  defaultfilemanager -D "$MOUNTPOINT" # -D = rox ...
  echo -e "\n ### UnMount: $imgFile\n"

  case "$mntinfo" in "/dev/mapper/luksfile"*)
      . /sbin/umount.crypto_LUKS 
      luks_umount "$mntinfo"
      ;;
    *)
      # better free loop device before calling umount...
      losetup -d ${MNTEDLOOP}
      case "$imgFile" in
         *.[w-W][i-I][m-M]) wimunmount --commit "$MOUNTPOINT" ;;
         *) umount "$MOUNTPOINT" ;;
      esac
      ;;
  esac

  Err=$?
  sync
  sleep 1
  if [ $Err -eq 0 ] ; then
    rm -rf "$MOUNTPOINT"
    /usr/lib/gtkdialog/box_splash -timeout 3 -bg green -text "$(gettext 'Unmounted') $imgFileBASE" #BK
  fi
fi

## ERROR: mount/unmount
if [ $Err -ne 0 ] ;then
  /usr/lib/gtkdialog/box_splash -timeout 3 -bg red -text "$(gettext 'Failed mounting or unmounting') $imgFileBASE" #BK
fi

###END###
